package com.itjin.health.controller;

import com.itjin.health.common.BaseResponse;
import com.itjin.health.common.ResultUtils;
import com.itjin.health.domain.dto.EmailRequest;
import com.itjin.health.service.CommonService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Slf4j
@Api(tags = "通用接口")
@RestController
public class CommonController {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private RedisTemplate redisTemplate;

    @Resource
    private CommonService commonService;

    /**
     * 验证码发送
     */
    @ApiOperation(value = "验证码发送", notes = "验证码发送")
    @PostMapping("/captcha")
    public BaseResponse<String> captcha(@RequestBody EmailRequest email) {
        // 生成验证码
        String verificationCode = generateVerificationCode();
        // 创建邮件对象
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("3338170081@qq.com"); // 发件人邮箱
        message.setTo(email.getEmail());
        message.setSubject("西南科技大学智能运动恢复系统 - 验证码");
        message.setText("您的验证码是：" + verificationCode + "\n验证码有效期为5分钟，请勿泄露给他人。");
        try {
            // 发送邮件
            mailSender.send(message);

            // 将验证码存入Redis，设置5分钟过期
            String redisKey = "email:code:" + email.getEmail();
            redisTemplate.opsForValue().set(redisKey, verificationCode, 5, TimeUnit.MINUTES);
            log.info("验证码发送成功！验证码：" + verificationCode);
            return ResultUtils.success("验证码发送成功！");
        } catch (Exception e) {
            System.out.println("验证码发送失败：" + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 生成6位随机验证码
     */
    private String generateVerificationCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }

    /**
     * 图片上传
     */
    @PostMapping("/uploadImage")
    @ApiOperation(value = "图片上传")
    public BaseResponse<String> uploadAvatar(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return (BaseResponse<String>) ResultUtils.error(400, "文件不能为空");
            }
            // 校验文件大小（例如：限制2MB）
            if (file.getSize() > 2 * 1024 * 1024) {
                return (BaseResponse<String>) ResultUtils.error(400, "文件大小不能超过2MB");
            }
            // 校验文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return (BaseResponse<String>) ResultUtils.error(400, "只能上传图片文件");
            }

            // 上传文件并获取访问URL
            String fileUrl = commonService.uploadFile(file);
            return ResultUtils.success(fileUrl);
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return (BaseResponse<String>) ResultUtils.error(500, "文件上传失败: " + e.getMessage());
        }
    }
}
